<template>
  <Category :scene="scene"/>
  <el-card style="margin: 20px 0">
    <div v-show="scene === 0">
      <el-button
        type="primary"
        size="default"
        icon="Plus"
        :disabled="!categoryStore.c3Id"
        @click="onAddAttr"
      >
        添加属性
      </el-button>
      <el-table border stripe style="margin-top: 20px" :data="attrArr">
        <el-table-column
          label="序号"
          type="index"
          align="center"
          width="80px"
        ></el-table-column>
        <el-table-column
          label="属性名称"
          align="center"
          width="200px"
          prop="attrName"
        ></el-table-column>
        <el-table-column label="属性值名称" align="center">
          <template #="{ row, $index }">
            <el-tag
              v-for="(item, index) in row.attrValueList"
              :key="item.id"
              style="margin: 5px"
            >
              {{ item.valueName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200px">
          <template #="{ row, $index }">
            <el-button
              type="warning"
              size="small"
              icon="Edit"
              @click="onEditAttr(row)"
            ></el-button>
            <el-popconfirm
              :title="`你确定删除${row.attrName}?`"
              width="200px"
              @confirm="onDeleteAttr(row.id)"
            >
              <template #reference>
                <el-button type="danger" size="small" icon="Delete"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div v-show="scene === 1">
      <el-form inline>
        <el-form-item label="属性名称">
          <el-input
            placeholder="请输入属性名称"
            v-model="attrParams.attrName"
          ></el-input>
        </el-form-item>
      </el-form>
      <el-button
        type="primary"
        icon="Plus"
        :disabled="!attrParams.attrName"
        @click="onAddAttrValue"
      >
        添加属性值
      </el-button>
      <!--      <el-button type="primary" @click="onCancel">取消</el-button>-->
      <el-table
        border
        stripe
        style="margin: 20px 0"
        :data="attrParams.attrValueList"
      >
        <el-table-column
          label="序号"
          type="index"
          align="center"
          width="80px"
        ></el-table-column>
        <el-table-column label="属性值名称" align="center" width="200px">
          <template #="{ row, $index }">
            <el-input
              :ref="(vc:any)=>inputArr[$index]=vc"
              placeholder="请输入属性值名称"
              v-model="row.valueName"
              size="small"
              v-if="row.flag"
              @blur="toLook(row, $index)"
            />
            <div v-else @click="toEdit(row, $index)">{{ row.valueName }}</div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200px">
          <template #="{ row, $index }">
            <el-button
              type="warning"
              size="small"
              icon="Delete"
              @click="attrParams.attrValueList.splice($index, 1)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button
        type="primary"
        @click="onSave"
        :disabled="attrParams.attrValueList.length === 0"
      >
        保存
      </el-button>
      <el-button type="primary" @click="onCancel">取消</el-button>
    </div>
  </el-card>
</template>
<script setup lang="ts">
import {
  nextTick,
  onBeforeMount,
  onBeforeUnmount,
  reactive,
  ref,
  watch,
} from 'vue'
// 获取分类的仓库
import useCategoryStore from '@/store/modules/category.ts'
// 引入获取已有属性与属性值接口
import {reqAddOrUpdateAttr, reqAttr, reqRemoveAttr} from '@/api/product/attr'
import {Attr, AttrResponseData, AttrValue} from '@/api/product/attr/type.ts'
import category from '@/store/modules/category.ts'
import {ElMessage} from 'element-plus'

let categoryStore = useCategoryStore()
// 存储已有的属性与属性值
let attrArr = ref<Attr[]>([])
// 定义卡片组件内容的切换
let scene = ref<number>(0)
// 收集新增的属性的数据
let attrParams = reactive<Attr>({
  attrName: '', // 新增属性的名字
  attrValueList: [], // 新增属性值的数组
  categoryId: '', // 三级分类的ID
  categoryLevel: 3, // 三级分类
})
//
let inputArr = ref<any>([])
// 获取已有的属性和属性值
const getAttr = async () => {
  // 获取分类的ID
  const {c1Id, c2Id, c3Id} = categoryStore
  let result: AttrResponseData = await reqAttr(c1Id, c2Id, c3Id)
  if (result.code === 200) attrArr.value = result.data
}
// 点击添加属性
const onAddAttr = () => {
  Object.assign(attrParams, {
    attrName: '', // 新增属性的名字
    attrValueList: [], // 新增属性值的数组
    categoryId: categoryStore.c3Id, // 三级分类的ID
    categoryLevel: 3, // 三级分类
  })
  scene.value = 1
}
// 点击修改属性
const onEditAttr = (row) => {
  scene.value = 1
  Object.assign(attrParams, JSON.parse(JSON.stringify(row)))
}
// 删除某一个已有的属性
const onDeleteAttr = async (attrId: number) => {
  let result: any = await reqRemoveAttr(attrId)
  if (result.code === 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    await getAttr()
  } else {
    ElMessage({
      type: 'success',
      message: '删除失败',
    })
  }
}
// 点击取消按钮
const onCancel = () => {
  scene.value = 0
}
// 点击保存按钮
const onSave = async () => {
  let result: any = await reqAddOrUpdateAttr(attrParams)
  if (result.code === 200) {
    scene.value = 0
    ElMessage({
      type: 'success',
      message: attrParams.id ? '修改成功' : '添加成功',
    })
    getAttr()
  } else {
    ElMessage({
      type: 'error',
      message: attrParams.id ? '修改失败' : '添加失败',
    })
  }
}
// 点击添加属性值
const onAddAttrValue = () => {
  attrParams.attrValueList.push({
    valueName: '',
    flag: true,
  })
  nextTick(() => {
    inputArr.value[attrParams.attrValueList.length - 1].focus()
  })
}
// 点击属性值div
const toEdit = (row: AttrValue, index: number) => {
  row.flag = true
  nextTick(() => {
    inputArr.value[index].focus()
  })
}
// 属性值表单失去焦点
const toLook = (row: AttrValue, index: number) => {
  if (row.valueName.trim() === '') {
    attrParams.attrValueList.splice(index, 1)
    ElMessage({
      type: 'error',
      message: '属性值不能为空',
    })
    return
  }
  // 判断是否有重复
  let repeat = attrParams.attrValueList.find((item) => {
    if (item != row) {
      return item.valueName === row.valueName
    }
  })
  if (repeat) {
    ElMessage({
      type: 'error',
      message: '属性值不能重复',
    })
    return
  }
  row.flag = false
}
// 监听仓库三级分类ID变化
watch(
  () => categoryStore.c3Id,
  () => {
    attrArr.value = []
    if (!categoryStore.c3Id) return
    getAttr()
  },
)
onBeforeUnmount(() => {
  categoryStore.$reset()
})
</script>
<style scoped lang="scss"></style>
